package com.imu.wys.controller;

import com.alibaba.fastjson.JSONObject;
import com.imu.wys.service.VoiceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

@Controller("VoiceController")
@RequestMapping(value = {"/voice"})
public class VoiceController {

    @Autowired
    VoiceService voiceService;

    @RequestMapping(value = "/score")
    public void index(HttpServletRequest request, HttpServletResponse response, String base64String, String text, int type) throws Exception {
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setCharacterEncoding("UTF-8");
        Map<String, Object> map = new HashMap<>();
        Map<String, Object> xmlMsg = new HashMap<>();
        text = text.replaceAll("\\pP|\\pS|\\pC|\\pN|\\pZ", "");
        try {
            if (type==1){
                xmlMsg = voiceService.getScore_Zh(text, base64String.substring("data:audio/mp3;base64,".length()));
            }else {
                xmlMsg = voiceService.getScore_En(text, base64String.substring("data:audio/mp3;base64,".length()));
            }
            map.put("code", 200);
            map.put("readText",text);
            if ((boolean) xmlMsg.get("is_rejected")) {
                map.put("code", 201);
            }
            JSONObject xmlMsgJson = new JSONObject(xmlMsg);
            map.put("xmlMsg", xmlMsgJson.toString());

        } catch (Exception e) {
            map.put("code", 100);
        }

        JSONObject json = new JSONObject(map);

        response.getWriter().print(json.toString());
    }

}
